package com.example.demo.service;

import com.example.demo.enums.BookStatus;
import com.example.demo.mapper.BookMapper;
import com.example.demo.model.BookInfo;
import com.example.demo.model.PageRequest;
import com.example.demo.model.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class BookService {
    @Autowired
    BookMapper bookMapper;

    public Integer insertBook(BookInfo bookInfo) {
        return bookMapper.insertBook(bookInfo);
    }

    public PageResult<BookInfo> getBookListByPage(PageRequest pageRequest) {
        //1.获取总记录数
        //2.获取当前页的记录
        Integer count = bookMapper.count();
        List<BookInfo> bookInfos = bookMapper.queryBookByPage(pageRequest.getOffset(), pageRequest.getPageSize());
        for(BookInfo bookInfo :bookInfos) {
            bookInfo.setStatusCN(BookStatus.getDescByCode(bookInfo.getStatus()).getDesc());
//            if(bookInfo.getStatus() == 2) {
//                bookInfo.setStatusCN("不可借阅");
//            }else {
//                bookInfo.setStatusCN("可借阅");
//            }
        }
        return new PageResult<BookInfo>(bookInfos, count, pageRequest);
    }

    /**
     * 根据ID查询图书信息
     * @param bookId
     * @return
     */
    public BookInfo queryBookById(Integer bookId) {
        long start = System.currentTimeMillis();
        BookInfo bookInfo =  bookMapper.queryBookById(bookId);
        bookInfo.setStatusCN(BookStatus.getDescByCode(bookInfo.getStatus()).getDesc());
        log.info("[BookService] queryBookById 耗时: " + (System.currentTimeMillis() - start) + " ms");
        return bookInfo;
    }

    /**
     * 更新图书
     * @param bookInfo
     * @return
     */
    public Integer updateBookById(BookInfo bookInfo) {
        return bookMapper.updateBookById(bookInfo);
    }

    public Integer deleteBook(Integer bookId) {
        BookInfo bookInfo = new BookInfo();
        bookInfo.setId(bookId);
        bookInfo.setStatus(0);
        return bookMapper.updateBookById(bookInfo);
    }

    public Integer batchDeleteBookById(List<Integer> ids) {
        return bookMapper.batchDeleteBookByIds(ids);
    }
}
